package com.example.dwb_homework6;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    WebView wv;
    SharedPreferences share;
    SharedPreferences.Editor shareEditor;
    ArrayList<String> history = new ArrayList<>();
    int i = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 启用窗口进度条功能
        getWindow().requestFeature(Window.FEATURE_PROGRESS);
        setContentView(R.layout.activity_main);

        EditText et = findViewById(R.id.et);
        final ListView lv = findViewById(R.id.lv);
        share = getSharedPreferences("com.sise.browser.history", MODE_PRIVATE);

        while (!share.getString("url_" + i, "").isEmpty()) {
            history.add(share.getString("url_" + i, ""));
            i += 1;
        }

        ArrayAdapter<String> ad = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, history);
        lv.setAdapter(ad);
        shareEditor = share.edit();

        // 初始化WebView
        wv = findViewById(R.id.wv);
        wv.getSettings().setJavaScriptEnabled(true);
        wv.getSettings().setBuiltInZoomControls(true);

        // 设置WebChromeClient处理进度条
        wv.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int newProgress) {
                // 设置进度值（范围0-10000）
                MainActivity.this.setProgress(newProgress * 100);
            }
        });

        // 设置WebViewClient处理链接跳转
        wv.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 在当前WebView中加载链接
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });

        // GO按钮事件处理
        Button btn = findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = et.getText().toString().trim();

                // 验证网址格式
                if (URLUtil.isNetworkUrl(url)) {
                    // 添加协议前缀（如果缺失）
                    if (!url.startsWith("http://") && !url.startsWith("https://")) {
                        url = "http://" + url;
                    }
                    wv.loadUrl(url);
                    // 添加到历史记录（去重）
                    if (!history.contains(url)) {
                        history.add(url);
                        shareEditor.putString("url_" + i, url).apply();
                        i += 1;
                    }
                } else {
                    Toast.makeText(MainActivity.this,
                            "网址格式错误，请检查输入", Toast.LENGTH_SHORT).show();
                    et.requestFocus();
                }
            }
        });

        // 前进按钮
        Button btnForward = findViewById(R.id.btnForward);
        btnForward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (wv.canGoForward()) {
                    wv.goForward();
                } else {
                    Toast.makeText(MainActivity.this,
                            "已到达最新页面", Toast.LENGTH_SHORT).show();
                }
            }
        });

        // 后退按钮
        Button btnBack = findViewById(R.id.btnBack);
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (wv.canGoBack()) {
                    wv.goBack();
                } else {
                    Toast.makeText(MainActivity.this,
                            "已到达最初页面", Toast.LENGTH_SHORT).show();
                }
            }
        });

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String url = history.get(position);
                wv.loadUrl(url);
                et.setText(url);
            }
        });
    }
}